package com.tyqx.hashchainbiz;

// import com.alibaba.fastjson.JSON;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tyqx.hashchainbean.module.*;
import com.tyqx.hashchainbean.vo.MongoDbInfoVO;
import com.tyqx.hashchainbiz.service.NoHashValueJsonService;
import hashchainutil.common.EmptyUtils;
import hashchainutil.common.JsonUtil;
import org.bson.types.ObjectId;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.json.JSONObject;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Component
public class SchedulerMongoDBLogistics {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private NoHashValueJsonService noHashValueJsonService;

    ///@Async
    //表示每隔秒
//    @Scheduled(fixedRate = 60 * 1000 * 10)
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(fixedDelay = 1000 * 11)
    public void testTasks() throws Exception {
        System.out.println("Logistics读取记录定时任务执行时间：" + dateFormat.format(new Date()));
        String collNameJl = "jztLogisticsList";
        CryptoPrimitives suite = new CryptoPrimitives();
        suite.init();
        Aggregation aggregationJlS = Aggregation.newAggregation(Aggregation.sample(1));
        AggregationResults<MongoDbInfoVO> mongoDbInfoVOJlS = mongoTemplate.aggregate(aggregationJlS, collNameJl, MongoDbInfoVO.class);
        MongoDbInfoVO mongoDbInfoVOJlSUnique = mongoDbInfoVOJlS.getUniqueMappedResult();
        //MongoDbInfoVO mongoDbInfoVOJlS = mongoTemplate.findOne(queryJl, MongoDbInfoVO.class, collNameJl);
        if (EmptyUtils.isNotEmpty(mongoDbInfoVOJlSUnique)) {
            List<NoHashValueJson> noHashValueJsonList=new ArrayList<>();
            String tableName = mongoDbInfoVOJlSUnique.getInfoTableName();
            if ("jzt_logistics".equals(tableName)) {
                List<JZTLogistics> jztLogisticsList = (List<JZTLogistics>) mongoDbInfoVOJlSUnique.getInfoList();
                int size = jztLogisticsList.size();
                for (int i = 0; i < size; i++) {
                    JZTLogistics jztLogistics = jztLogisticsList.get(i);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    jztLogistics.setCreateTime(createTime);
                    jztLogistics.setUpdateTime(createTime);
                    Gson gson = new GsonBuilder()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss")
                            .create();
                    JSONObject jsonObject = new JSONObject(gson.toJson(jztLogistics));
                    jsonObject = JsonUtil.getSortJson(jsonObject);
                    String jztLogisticsStr = jsonObject.toString();

                    NoHashValueJson noHashValueJson = new NoHashValueJson();
                    noHashValueJson.setRecordJson(jztLogisticsStr);
                    noHashValueJson.setHashTableName("jzt_logistics");
                    noHashValueJson.setUserName(jztLogistics.getUserName());
                    byte[] hashBytes = suite.hash(jztLogisticsStr.getBytes());
                    String hashValue = Base64.getEncoder().encodeToString(hashBytes);

                    noHashValueJson.setHashValue(hashValue);

                    noHashValueJson.setStatus(0);

                    noHashValueJsonList.add(noHashValueJson);
                }
            }
            /*else if ("jzt_code_circulation".equals(tableName)) {
                List<JZTCodeCirculation> jztCodeCirculationList = (List<JZTCodeCirculation>) mongoDbInfoVOJlSUnique.getInfoList();
                int size = jztCodeCirculationList.size();
                for (int i = 0; i < size; i++) {
                    JZTCodeCirculation jztCodeCirculation = jztCodeCirculationList.get(i);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    jztCodeCirculation.setCreateTime(createTime);
                    jztCodeCirculation.setUpdateTime(createTime);
                    Gson gson = new GsonBuilder()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss")
                            .create();
                    JSONObject jsonObject = new JSONObject(gson.toJson(jztCodeCirculation));
                    jsonObject = JsonUtil.getSortJson(jsonObject);
                    String jztLogisticsStr = jsonObject.toString();

                    NoHashValueJson noHashValueJson = new NoHashValueJson();
                    noHashValueJson.setRecordJson(jztLogisticsStr);
                    noHashValueJson.setHashTableName("jzt_code_circulation");
                    noHashValueJson.setUserName(jztCodeCirculation.getUserName());
                    byte[] hashBytes = suite.hash(jztLogisticsStr.getBytes());
                    String hashValue = Base64.getEncoder().encodeToString(hashBytes);

                    noHashValueJson.setHashValue(hashValue);

                    noHashValueJson.setStatus(0);

                    noHashValueJsonList.add(noHashValueJson);
                }
            }else if ("jzt_GS1".equals(tableName)) {
                List<JZTGS1> jztgs1List = (List<JZTGS1>) mongoDbInfoVOJlSUnique.getInfoList();
                int size = jztgs1List.size();
                for (int i = 0; i < size; i++) {
                    JZTGS1 jztgs1 = jztgs1List.get(i);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    jztgs1.setCreateTime(createTime);
                    jztgs1.setUpdateTime(createTime);
                    Gson gson = new GsonBuilder()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss")
                            .create();
                    JSONObject jsonObject = new JSONObject(gson.toJson(jztgs1));
                    jsonObject = JsonUtil.getSortJson(jsonObject);
                    String jztLogisticsStr = jsonObject.toString();

                    NoHashValueJson noHashValueJson = new NoHashValueJson();
                    noHashValueJson.setRecordJson(jztLogisticsStr);
                    noHashValueJson.setHashTableName("jzt_GS1");
                    noHashValueJson.setUserName(jztgs1.getUserName());
                    byte[] hashBytes = suite.hash(jztLogisticsStr.getBytes());
                    String hashValue = Base64.getEncoder().encodeToString(hashBytes);

                    noHashValueJson.setHashValue(hashValue);

                    noHashValueJson.setStatus(0);

                    noHashValueJsonList.add(noHashValueJson);
                }
            }*/
            Integer flag=noHashValueJsonService.insertNoHashValueJsonBatch(noHashValueJsonList);

            if(flag>0){
                Query removeQuery = new Query();
                String mongoDBId = mongoDbInfoVOJlSUnique.getId();
                ObjectId objectId = new ObjectId(mongoDBId);
                Criteria criteria = Criteria.where("_id").is(objectId);
                removeQuery.addCriteria(criteria);
                mongoTemplate.remove(removeQuery, MongoDbInfoVO.class, collNameJl);
            }
        }

        System.out.println("Logistics读取记录定时任务结束时间：" + dateFormat.format(new Date()));

    }

}